import logging
import os
import os.path

from string import split
from pylons import request, response, session, tmpl_context as c
from pylons.controllers.util import abort, redirect_to
from pylons import config

from authkit.authorize.pylons_adaptors import authorize, authorized
from authkit.permissions import HasAuthKitRole, RemoteUser, ValidAuthKitUser, UserIn

from arkaiv.model.oggzinfo import OggzInfo
from arkaiv.lib.base import BaseController, render, model

log = logging.getLogger(__name__)

path_base = config['media_path_base']
media_url_base = config['media_url_base']

class PlaylistController(BaseController):

    def index(self):
        # Return a rendered template
        #return render('/playlist.mako')
        # or, return a response
        return 'Hello World'

    def playlistpage(self):
        """ controller for the main playlist listing page

        """
        c.playlists=model.getplaylists()
        return render('/playlists.mak')

    def addplaylist(self):
        """ Controller to add a new playlist

        """
        model.addnewplaylist(request.params['newplaylist'])
        c.playlists = model.getplaylists()
        return render('/playlists.mak')

    def deleteplaylist(self):
        name = request.params['playlistname']
        model.deleteplaylist(name)

        redirect_to(action='playlistpage')

    def displayplaylist(self):
        if authorized(HasAuthKitRole('admin')):
            role = "admin"
        else:
            role = "public"
# Need to extract appropriate info for the playlist selected
        playlistid = int(request.params['id'])
#        print "playlist id is \n\n"
        c.name = request.params['name']        
        clips = model.getclipsfromplaylist(playlistid,role)
        items = model.getitemsfromplaylist(playlistid,role)
        # send a list of dictionaries to the template
        for clip in clips:
            if (clip != None):
                item = model.getitemforclip(clip['index'])
                clip['name'] = item.name  #name of the item the clip belongs to
                sourceid = model.getsourcesforitem(item.ixi)
                oggsource = model.getsourcepath(sourceid)
                cmmlfile = model.getitemcmmlfile(item.ixi)
                urlpath = split(cmmlfile, path_base)
                # Now split off the extension
                urlpath = os.path.splitext(urlpath[1])[0]
                #clip['url'] = media_url_base + urlpath + ".anx" + "?id=" + clip['id']
                o = OggzInfo(oggsource)
                if (o.has_video()):
                    clip['has_video'] = "Yes"
                else:
                    clip['has_video'] = "No"
                    
                if (o.has_audio()):
                    clip['has_audio'] = "Yes"
                else:
                    clip['has_audio'] = "No" 
 
                if clip['end'] == 0:
                  clip['url'] = media_url_base + urlpath + ".ogg" + "?t=" + str(clip['start'])
                else:
                  clip['url'] = media_url_base + urlpath + ".ogg" + "?t=" + str(clip['start']) + "/" + str(clip['end'])
                   
        for item in items:
            sourceid = model.getsourcesforitem(item['index'])
            oggsource = model.getsourcepath(sourceid)
            urlpath = split(item['cmmlfile'], path_base)
            # Now split off the extension
            urlpath = os.path.splitext(urlpath[1])[0]
            #clipimageurl = media_url_base + os.path.dirname(urlpath) + "/"
            item['id'] = ""    # a dummy to match clip info
            #item['url'] = media_url_base + urlpath + ".anx" + "?id=0"
            item['url'] = media_url_base + urlpath + ".ogg"
            clips.append(item)

        c.clips = clips 
        print c.clips
        if (not c.clips):
            print "Nothing in clips"
            return render ('/emptyplaylistmessage.mak')
        else:
            return render('/playlistview.mak')

    def additemstoplaylist(self):
        nmetas = int(request.params['nummetas'])
        playlist = request.params['playlist']
        for i in range(nmetas):
            try:
                itemid = request.params[str(i)]
                model.additemtoplaylist(playlist, itemid)
            except:
                pass

        redirect_to(controller='playlist', action='playlistpage')


    def addclipstoplaylist(self):
        nclips = int(request.params['numclips'])
        playlist = request.params['playlist']
        for i in range(nclips):
            try:
                clipid = request.params[str(i)]
                model.addcliptoplaylist(playlist, clipid)
            except:
                pass

        redirect_to(controller='playlist', action='playlistpage')


